import common from "../common.js"
Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    fileList: [],
    obj:{
      picArr: [],
      userName: '',
      content: '',
      imageArr: []
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {

    uploadImage(url){
      var fileName = "articleImg/"+common.ranFile()+common.houZhui(url)
      return new Promise((resolve) => {
        wx.cloud.uploadFile({
          cloudPath:fileName,
          filePath:url
        }).then((res) => {
          resolve(res)
        })
      })
    },


    async onSubmit(e){

      wx.showLoading({
        title: '数据提交中...',
        mask:true
      })

      if (this.data.fileList.length){
        for (let i = 0; i < this.data.fileList.length; i++) {
        const res = await this.uploadImage(this.data.fileList[i].url)
        this.data.obj.picArr.push(res.fileID)
      }
      
      }
      
      var userInfo = wx.getStorageSync('userInfo');
      this.data.obj.content = e.detail.value.content
      this.data.obj.userName = userInfo.nickName
      this.data.obj.head = userInfo.avatarUrl
      wx.cloud.callFunction({
        name:"articleAddOne",
        data:{
          obj:this.data.obj
        }
      }).then(res=>{
        wx.hideLoading();
        wx.showToast({
          title: '发布成功',
          mask:true
        })
        setTimeout(()=>{
          wx.redirectTo({
                    url: '/pages/index/index',
                  })
        },1500)
      })
    },

    
    delPic(e){
      var index = e.detail.index;
      var newList = this.data.fileList
      newList.splice(index,1)
      this.setData({
        fileList: newList
      })
    },

    afterRead(p){
      this.setData({
        fileList:p.detail.file
      })
    }
  }
})
